package com.shadow.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.shadow.common.entity.RolePermission;
import com.shadow.mapper.PermissionMapper;
import com.shadow.common.entity.Permission;
import com.shadow.mapper.RolePermissionMapper;
import com.shadow.service.PermissionService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by shadow
 * on 2022-6-29.
 */
@Service
public class PermissionServiceImpl implements PermissionService {

    @Resource
    private PermissionMapper permissionMapper;
    @Resource
    private RolePermissionMapper rolePermissionMapper;

    /**
     * 通过角色获取权限列表
     *
     * @param roleId 角色id
     * @return {@link List} 权限列表
     */
    @Override
    public List<Permission> getPermissionListByRoleId(final String roleId) {
        LambdaQueryWrapper<RolePermission> rolePermissionWrapper = new LambdaQueryWrapper<RolePermission>()
                .eq(RolePermission::getRoleId, roleId);
        List<RolePermission> rolePermissionList = rolePermissionMapper.selectList(rolePermissionWrapper);
        if (CollectionUtils.isNotEmpty(rolePermissionList)) {
            LambdaQueryWrapper<Permission> roleWrapper = new LambdaQueryWrapper<Permission>()
                    .in(Permission::getId, rolePermissionList.stream().map(RolePermission::getPermissionId).collect(Collectors.toList()));
            return Collections.unmodifiableList(permissionMapper.selectList(roleWrapper));
        }
        return Collections.emptyList();
    }

    /**
     * 根据用户获取权限列表
     *
     * @param userAccount 用户账户
     * @return {@link List} 权限列表
     */
    @Override
    public List<Permission> getPermissionListByUserAccount(final String userAccount) {
        return permissionMapper.getPermissionListByUserAccount(userAccount);
    }
}
